package apigateway.project.register.listener;

import apigateway.project.commen.config.ServiceDefinition;
import apigateway.project.commen.config.ServiceInstance;
import apigateway.project.register.Interface.RegisterCenterListener;
import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingMaintainService;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.Service;
import lombok.Setter;

import java.util.HashSet;
import java.util.List;

public class NacosServiceListener implements EventListener {

    @Setter
    private NamingMaintainService namingMaintainService;
    @Setter
    private NamingService namingService;
    @Setter
    private String env;
    @Setter
    private RegisterCenterListener registerCenterListener;
    public NacosServiceListener(NamingMaintainService namingMaintainService, NamingService namingService, String env,RegisterCenterListener registerCenterListener) {
        this.namingMaintainService = namingMaintainService;
        this.namingService = namingService;
        this.env = env;
        this.registerCenterListener = registerCenterListener;
    }


    @Override
    public void onEvent(Event event) {
        //判断是否是注册中心事件
        if(event instanceof NamingEvent) {
            NamingEvent namingEvent = (NamingEvent) event;
            //获得使事件发生的服务名
            String serviceName = namingEvent.getServiceName();
            try {
                //获得服务
                Service service = namingMaintainService.queryService(serviceName, env);
                //获得服务定义信息
                ServiceDefinition serviceDefinition = JSON.parseObject(service.getMetadata().get("meta"), ServiceDefinition.class);
                //获得服务的所有实例
                List<Instance> allInstances = namingService.getAllInstances(serviceName, env);
                HashSet<ServiceInstance> set = new HashSet<>();
                allInstances.forEach(x->{
                    ServiceInstance serviceInstance = JSON.parseObject(x.getMetadata().get("meta"), ServiceInstance.class);
                    set.add(serviceInstance);
                });
                registerCenterListener.onVarify(serviceDefinition,set);

            } catch (NacosException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
